package org.example.ymcc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.example.ymcc.constant.MQConstants;
import org.example.ymcc.constant.RConst;
import org.example.ymcc.domain.PayFlow;
import org.example.ymcc.domain.PayOrder;
import org.example.ymcc.mapper.PayFlowMapper;
import org.example.ymcc.mapper.PayOrderMapper;
import org.example.ymcc.service.IPayOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zcj
 * @since 2024-06-21
 */
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {



    @Autowired
    private PayFlowMapper payFlowMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void paySuccess(Map<String, String> newMp) throws ParseException {
        //支付单状态修改   记录支付流水
        String orderSn = newMp.get("out_trade_no");
        PayOrder one = super.getOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderNo, orderSn));
        one.setPayStatus(RConst.Num.INT_1);
        super.updateById(one);
        //记录支付流水
        PayFlow payFlow = new PayFlow();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        payFlow.setNotifyTime(sdf.parse(newMp.get("gmt_payment")));
        payFlow.setSubject(newMp.get("subject"));
        payFlow.setOutTradeNo(orderSn);
        payFlow.setTotalAmount(new BigDecimal(newMp.get("total_amount")));
        payFlow.setTradeStatus(newMp.get("trade_status"));
        payFlow.setPaySuccess(RConst.Num.INT_1);
        payFlow.setResultDesc("交易成功");
        payFlowMapper.insert(payFlow);

        //两种方案  一个 使用MQ来进行修改   二 使用openfeign
        //订单状态修改   订单号
        //保存用户购买记录 订单号 courseid    userId
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderSn",orderSn);
        map.put("courseId",one.getRelationId());
        map.put("userId",one.getUserId());
        rocketMQTemplate.syncSend(MQConstants.ALI_PAY_CALLBACK_ORDER_TOPIC+":"+
                MQConstants.ALI_PAY_CALLBACK_ORDER_TAG,
                MessageBuilder.withPayload(JSONObject.toJSONString(map)).build());
    }
}
